import type { App } from "vue";
import { Directive, DirectiveBinding } from "vue";
import { useUserStore } from "@/store/modules/user";
import { judementSameArr } from "@/utils/array";
/**
 * 按钮权限
 */

// export const hasPerm: Directive = {
//   mounted(el: HTMLElement, binding: DirectiveBinding) {
//     const stores = useUserStore();
//     if (!stores.user.permissions.some((v: Record<string, any>) => v === binding.value)) el.parentNode.removeChild(el)
//   },
// };

/**
 * 用户权限指令
 * @directive 单个权限验证（v-auth="xxx"）
 * @directive 多个权限验证，满足一个则显示（v-auths="[xxx,xxx]"）
 * @directive 多个权限验证，全部满足则显示（v-auth-all="[xxx,xxx]"）
 */
export function authDirective(app: App) {
  // 单个权限验证（v-auth="xxx"）
  app.directive("auth", {
    mounted(el, binding) {
      const stores = useUserStore();
      if (
        !stores.user.permissions.some(
          (v: Record<string, any>) => v === binding.value
        )
      )
        el.parentNode.removeChild(el);
    },
  });

  // 多个权限验证，满足一个则显示（v-auths="[xxx,xxx]"）
  app.directive("auths", {
    mounted(el, binding) {
      let flag = false;
      const stores = useUserStore();
      stores.user.permissions.map((val: Record<string, any>) => {
        binding.value.map((v: Record<string, any>) => {
          if (val === v) flag = true;
        });
      });
      if (!flag) el.parentNode.removeChild(el);
    },
  });

  // 多个权限验证，全部满足则显示（v-auth-all="[xxx,xxx]"）
  app.directive("auth-all", {
    mounted(el, binding) {
      const stores = useUserStore();
      const flag = judementSameArr(binding.value, stores.user.permissions);
      if (!flag) el.parentNode.removeChild(el);
    },
  });
}
